<template>
	<view class="content">
		<view class="navbar">
			<view v-for="(item, index) in navList" :key="index" class="nav-item" :class="{current: tabCurrentIndex === index}"
			 @click="tabClick(index)">
				{{item.text}}
			</view>
		</view>

		<swiper :current="tabCurrentIndex" class="swiper-box" duration="300" @change="changeTab">
			<swiper-item class="tab-content" v-for="(tabItem,tabIndex) in navList" :key="tabIndex">
				<scroll-view class="list-scroll-content" scroll-y @scrolltolower="loadData">
					<!-- 空白页 -->
					<empty v-if="tabItem.loaded === true && tabItem.orderList.length === 0"></empty>
					<!-- 订单列表 -->
					<view v-for="(item,index) in tabItem.orderList" :key="index" class="order-item" @click="toDetail(item)">
						<view class="i-top b-b">
							<text class="time">{{item.createTime}}</text>
							<text class="state" :style="{color: item.stateTipColor}">{{item.status}}</text>
							<text v-if="item.state===9" class="del-btn yticon icon-iconfontshanchu1" @click.stop="deleteOrder(index)"></text>
						</view>
						<block v-for="(goodsItem, goodsIndex) in item.list" :key="goodsIndex">
							<view class="goods-box-single">
								<image class="goods-img" :src="goodsItem.goodsImg" mode="aspectFill"></image>
								<view class="right">
									<text class="title clamp">{{goodsItem.goodsName}}</text>
									<text class="attr-box">{{goodsItem.goodsPrice}} x {{goodsItem.goodsNum}}</text>
									<text class="price">{{goodsItem.goodsPrice}}</text>
								</view>
							</view>
							<view class="comment">
								<button class="commentContent" v-if="item.orderStatus == 2 && item.isAppraise == 0 && goodsItem.appraise==null"
								 @click.stop="toComment(goodsItem)">评价</button>

								<button class="commentContent" v-if="goodsItem.appraise!=null" @click.stop="showComment(goodsItem,item.shopName)">查看评价</button>
							</view>
						</block>


						<view class="price-box">
							共
							<text class="num">{{item.list.length}}</text>
							件商品 实付款
							<text class="price">{{item.realTotalMoney}}</text>
						</view>

						<view class="action-box b-t" v-if="item.state != 9">

							<button class="action-btn recom" v-if="item.orderStatus == 1" @click.stop="recive(item.orderId)">确认收货</button>
							<!-- <button class="action-btn" v-if="item.orderStatus == 1">拒收</button> -->

							<button class="action-btn" v-if="item.allowRefund == 1 && (item.orderStatus == -1 || item.orderStatus == -3)">申请退款</button>

							<button class="action-btn" v-if="item.orderStatus == 2 && item.canAfterSale">申请售后</button>



							<button class="action-btn" v-if="(item.orderStatus != -1 || item.orderStatus == 1) && item.orderStatus !=2 && item.isComplain == 0">投诉</button>
							<button class="action-btn" v-if="item.orderStatus == -2 || item.orderStatus == 0" @click.stop="openPoup(item)">取消订单</button>

							<button class="action-btn" v-if="item.orderStatus == 0 && item.noticeDeliver == 0" @click.stop="noticeDeliver(item)">提醒发货</button>

							<button class="action-btn recom" v-if="item.orderStatus == -2" @click.stop="choicePay(item.pkey)">立即支付</button>
						</view>
					</view>

					<uni-load-more :status="tabItem.loadingType"></uni-load-more>

				</scroll-view>
			</swiper-item>
		</swiper>
		<uniPopup ref='poup' withMask type="bottom">
			<view class="cancleTitle">
				取消订单
			</view>
			<view class="content_trouble">
				<view class="desc">
					请选择你取消订单的原因
				</view>
				<radio-group @change="radioChange">
					<view class="resonItme" v-for="(item,index) in resons" @click="tabReson(index)">
						<view class="resconContext">
							{{item.dataName}}
						</view>
						<radio :checked="index === resonIndex" color="#fa436a"></radio>
					</view>
				</radio-group>
				<view class="bottom">
					<view class="cancle" @click="closePoup()">
						取消
					</view>
					<view class="confirm" @click="cancelOrder()">
						确定
					</view>
				</view>
			</view>
		</uniPopup>
	</view>
</template>

<script>
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	import empty from "@/components/empty";
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import Json from '@/Json';
	export default {
		components: {
			uniLoadMore,
			empty,
			uniPopup
		},
		data() {
			return {
				resonIndex: 0,
				resons: [],
				calcelItem: {},
				tabCurrentIndex: 0,
				pagesize: 15,
				navList: [{
						state: 0,
						text: '全部',
						loadingType: 'more',
						type: '',
						page: 0,
						orderList: []
					},
					{
						state: 1,
						text: '待付款',
						loadingType: 'more',
						type: 'waitPay',
						page: 0,
						orderList: []
					},
					{
						state: 2,
						text: '待发货',
						loadingType: 'more',
						type: 'waitDeliver',
						page: 0,
						orderList: []
					},
					{
						state: 3,
						text: '待收货',
						loadingType: 'more',
						type: 'waitReceive',
						page: 0,
						orderList: []
					},
					{
						state: 4,
						text: '待评价',
						loadingType: 'more',
						type: 'waitAppraise',
						page: 0,
						orderList: []
					},
					{
						state: 5,
						text: '已完成',
						loadingType: 'more',
						type: 'finish',
						page: 0,
						orderList: []
					}
				],
			};
		},
		onLoad(options) {
			/**
			 * 修复app端点击除全部订单外的按钮进入时不加载数据的问题
			 * 替换onLoad下代码即可
			 */
			this.tabCurrentIndex = +options.state || 0;
			// #ifndef MP
			this.loadData()
			// #endif
			// #ifdef MP
			if (options.state == 0) {
				this.loadData()
			}
			// #endif
			this.loadData()
			this.getIndex()
		},
		onPullDownRefresh: function() {
			console.log('refresh');
			let that = this;
			this.loadData()
		},
		methods: {

			showComment(item, shopName) {
				// console.log(item)
				let param = {
					goodsId: item.goodsId,
					specId: item.goodsSpecId,
					orderId: item.orderId,
					orderGoodsId: item.id,
					shopName: shopName,
					img: item.goodsImg,
					goodsName: item.goodsName
				}
				uni.navigateTo({
					url: '/subPackage/showComment/showComment?param=' + JSON.stringify(param)
				})
			},
			toComment(item) {
				uni.navigateTo({
					url: '../../subPackage/comment/comment?goods=' + JSON.stringify(item)
				})
			},
			toDetail(item) {
				uni.navigateTo({
					url: '/pages/detail/detail?id=' + item.orderId
				})
			},
			// 选择取消订单原因
			radioChange(e) {
				console.log(e)
				this.resonIndex = e.detail.value
			},
			tabReson(index) {
				this.resonIndex = index
			},
			//获取订单列表	
			loadData(source, reset = false) {
				//这里是将订单挂载到tab列表下
				let index = this.tabCurrentIndex;
				let navItem = this.navList[index];
				let state = navItem.state;

				if (reset) {
					--navItem.page
					navItem.orderList = []
				}

				if (source === 'tabChange' && navItem.loaded === true) {
					//tab切换只有第一次需要加载数据
					// return;
				}
				if (navItem.loadingType === 'loading') {
					//防止重复加载
					return;
				}

				navItem.loadingType = 'loading';

				setTimeout(() => {
					// let orderList = Json.orderList.filter(item=>{
					// 	//添加不同状态下订单的表现形式
					// 	item = Object.assign(item, this.orderStateExp(item.state));
					// 	//演示数据所以自己进行状态筛选
					// 	if(state === 0){
					// 		//0为全部订单
					// 		return item;
					// 	}
					// 	return item.state === state
					// });
					// orderList.forEach(item=>{
					// 	navItem.orderList.push(item);
					// })
					// //loaded新字段用于表示数据加载完毕，如果为空可以显示空白页
					// this.$set(navItem, 'loaded', true);

					let params = {
						pagesize: this.pagesize,
						page: ++navItem.page,
						type: navItem.type
					}

					uni.stopPullDownRefresh()
					this.$Request.request('/api/orders/getOrderList', 'POST', params, true).then(res => {
						console.log(res)
						if (res.status == 1) {
							let orderlist = res.data.data


							if (orderlist.length == 0) {
								--navItem.page
								navItem.loadingType = 'noMore';
								this.$set(navItem, 'loaded', true)
								return
							}

							orderlist.forEach(item => {
								navItem.orderList.push(item);
							})
							console.log(navItem)
							this.$set(navItem, 'loaded', true)
						}

					}).catch(err => {
						console.log(err)
					})
					//判断是否还有数据， 有改为 more， 没有改为noMore 
					navItem.loadingType = 'more';
				}, 600);
			},
			getIndex() {
				this.$Request.request('/api/orders/index', 'GET', {}, true).then(res => {
					if (res.status == 1) {

						this.resons = res.data.order_cancel
					}
				}).catch(err => {

				})
			},
			recive(id) {
				uni.showModal({
					title: "确认收货",
					content: '你确认收货吗？',
					success: (res) => {
						if (res.confirm) {
							// this.$api.msg("你点击了确认")
							this.$Request.request('/api/orders/receive', 'POST', {
								id
							}, true).then(res => {
								if (res.status == 1) {
									this.$api.msg(res.msg)
									this.loadData('', true)
								}
							}).catch(err => {
								console.log(err)
							})
						} else if (res.cancel) {
							// this.$api.msg("点击了取消")
						}
					}
				})
			},
			//swiper 切换
			changeTab(e) {
				this.tabCurrentIndex = e.target.current;
				this.loadData('tabChange', true);
			},
			//顶部tab点击
			tabClick(index) {
				this.tabCurrentIndex = index;
			},
			//删除订单
			deleteOrder(index) {
				uni.showLoading({
					title: '请稍后'
				})
				setTimeout(() => {
					this.navList[this.tabCurrentIndex].orderList.splice(index, 1);
					uni.hideLoading();
				}, 600)
			},
			openPoup(item) {
				this.calcelItem = item
				this.$refs.poup.open()
			},
			closePoup() {
				this.calcelItem = {}
				this.$refs.poup.close()
			},
			//取消订单
			cancelOrder() {
				let item = this.calcelItem
				let reson = this.resons[this.resonIndex]

				uni.showLoading({
					title: '请稍后'
				})
				setTimeout(() => {
					this.$Request.request('/api/orders/cancellation', 'POST', {
						id: item.orderId,
						reason: reson.id
					}, true).then(res => {
						if (res.status == 1) {
							this.$api.msg(res.msg)
							this.loadData('', true)
							uni.hideLoading();
							this.closePoup()
						}

					}).catch(err => {
						console.log(err)
					})
				}, 600)
			},

			//订单状态文字和颜色
			orderStateExp(state) {
				let stateTip = '',
					stateTipColor = '#fa436a';
				switch (+state) {
					case 1:
						stateTip = '待付款';
						break;
					case 2:
						stateTip = '待发货';
						break;
					case 9:
						stateTip = '订单已关闭';
						stateTipColor = '#909399';
						break;

						//更多自定义
				}
				return {
					stateTip,
					stateTipColor
				};
			},
			// 立即支付
			choicePay(pkey) {
				uni.redirectTo({
					url: '../money/pay?pkey=' + pkey
				})
			},
			// 提醒发货
			noticeDeliver(item) {
				uni.showLoading({
					title: '请稍后'
				})
				setTimeout(() => {
					this.$Request.request('/api/orders/noticeDeliver', 'POST', {
						id: item.orderId,
					}, true).then(res => {
						if (res.status == 1) {
							this.$api.msg(res.msg)
							this.loadData('', true)
							uni.hideLoading();
						}

					}).catch(err => {
						console.log(err)
					})
				}, 600)
			}
		},
	}
</script>

<style lang="scss">
	@import './order.scss'
</style>
